﻿using System;
using System.Collections.Generic;
using MySql.Data.MySqlClient;
using eStock.SQL;

namespace eStock.DataObjects
{
    public static class DatabaseObjects
    {
        public static AddressCollection Addresses { get; private set; }
        public static ComponentCategoryCollection Categories { get; private set; }
        public static ComponentCollection Components { get; private set; }
        public static TrayCollection Trays { get; private set; }
        public static ComponentTypeCollection Types { get; private set; }
        public static ImageCollection Images { get; private set; }
        public static OrderCollection Orders { get; private set; }
        public static ProjectCollection Projects { get; private set; }
        
        /// <summary>
        /// Key = title, Value = value
        /// </summary>
        public static Dictionary<string, string> Config;


        static DatabaseObjects()
        {
            Addresses = new AddressCollection();
            Categories = new ComponentCategoryCollection();
            Components = new ComponentCollection();
            Trays = new TrayCollection();
            Types = new ComponentTypeCollection();
            Images = new ImageCollection();
            Orders = new OrderCollection();
            Projects = new ProjectCollection();
            Config = new Dictionary<string, string>();
        }

        public static bool UpdateConfig()
        {
            try
            {
                foreach (KeyValuePair<string, string> c in Config)
                {
                    SQLDataReader res = MainWindow.Database.QueryRead("SELECT * FROM es_config WHERE title = " + c.Key);
                    int i = MainWindow.Database.FetchCount(res);
                    if (i == 0)
                    {
                        MainWindow.Database.QueryWrite("INSERT INTO es_config (title, value) VALUES ('" + MainWindow.Database.EscapeString(c.Key) + "', '" + MainWindow.Database.EscapeString(c.Value) + "');");
                    }
                    else
                    {
                        MainWindow.Database.QueryWrite("UPDATE es_config SET value = '" + MainWindow.Database.EscapeString(c.Value) + "' WHERE title = '" + c.Key + "';");
                    }
                }
                return true;
            }
            catch (Exception)
            {
#if DEBUG
                throw new Exception("Failed to update config table");
#else
                return false;
#endif
            }
        }
    }
}
